package de.mmis.utilities.genericPublisher;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;

import de.mmis.core.infrastructure.DistributedInfrastructure;

/**
 * Simple {@link JFrame} containing a {@link JComboBox} from which the user can
 * select a bind address for the {@link DistributedInfrastructure}
 * 
 * @author Martin Nyolt
 * 
 */
public class SelectBindAddressDialog extends JDialog {

	private InetAddress selectedAddress = null;

	public SelectBindAddressDialog(JFrame owner) {
		super(owner, "Select bind address");

		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		initGUI();
	}

	private void initGUI() {
		setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));

		List<InetAddress> addresses = DistributedInfrastructure
				.getPossibleBindAddresses();

		final JComboBox box = new JComboBox(addresses.toArray());
		add(box);

		JButton ok = new JButton("OK");
		ok.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				selectedAddress = (InetAddress) box.getSelectedItem();
				dispose();
			}
		});
		add(ok);

		JButton cancel = new JButton("Cancel");
		cancel.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				selectedAddress = null;
				dispose();
			}
		});
		add(cancel);

		pack();
		setResizable(false);
	}

	/**
	 * @return the selected address, or <code>null</code> if the user selected
	 *         none.
	 */
	public InetAddress getSelectedAddress() {
		return selectedAddress;
	}

}
